'''
Created on Jun 3, 2010

@author: oabalbin
'''

import numpy as np
import scipy as sp
from scipy import stats
from collections import deque, defaultdict

def calculate_FDR(pvalues_array):
    """
    It returns a FDR for the array of pvalues
    
    # Start by sorting all rows in increasing order of t-test p-values for the brain (adult vs. fetal) analysis.
    # Note the number of probesets we're analyzing
    # Copy the last raw p-value into the column of FDR p-values.
    # For the fields above the last, apply the formula
    fdr = min(raw * (num_rows/rank_this_probeset), fdr_for_gene_one_row_below)
    ex: =MIN(B7923 * 7923/RANK(B7923,B$2:B7924,1),F7924)
    Note that the rank is calculated for the list of raw p-values in ascending order.
    # Paste this formula in the cells above to correct for all probesets.
    """
    
    number_of_test=len(pvalues_array)
    pvalues_array2sort = np.copy(pvalues_array)
    inidicators = np.array(range(number_of_test))
    sort_indicators = np.argsort(pvalues_array2sort)  
    qvalue_array = np.empty((number_of_test,2))
    # sort the original pvalues
    pvalues_array2sort.sort()
    
    First=True
    for i in inidicators[::-1]:
        rank=i+1
        if First:
            qvalue_array[i,0] = pvalues_array2sort[i]
            qvalue_array[i,1] = pvalues_array2sort[i]
            First=False
        else:
            qvalue_array[i,0] = pvalues_array2sort[i]
            pvalue=pvalues_array2sort[i]
            #print pvalue, pvalue*(number_of_test/float(rank)), qvalue_array[i+1,1], np.minimum( pvalue*(number_of_test/float(rank)), qvalue_array[i+1,1] )
            qvalue_array[i,1] = np.minimum( pvalue*(number_of_test/float(rank)), qvalue_array[i+1,1] )
    
    qvalue_array = qvalue_array[sort_indicators,:]
    return qvalue_array#, sort_indicators


'''
pvalues_array = myarray = np.random.uniform(low=0.0,high=1.0,size=1000)
qvalue_array = calculate_FDR(pvalues_array)
print qvalue_array
'''
    

